package com.futvan.z.system.zform;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import com.futvan.z.framework.common.bean.Code;
import com.futvan.z.framework.common.bean.Result;
import com.futvan.z.system.zcode.z_code;
import com.futvan.z.system.zcode.z_code_detail;
import com.futvan.z.system.zform.z_form_table;
import com.futvan.z.system.zform.z_form_table_button;
import com.futvan.z.system.zvcode.z_vcode;

import jxl.Cell;
import jxl.CellView;
import jxl.Sheet;
import jxl.SheetSettings;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.format.VerticalAlignment;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import com.futvan.z.framework.common.service.CommonService;
import com.futvan.z.framework.core.SuperAction;
import com.futvan.z.framework.core.z;
import com.futvan.z.framework.util.DateUtil;
import com.futvan.z.framework.util.FileUtil;
import com.futvan.z.framework.util.HttpUtil;
import com.futvan.z.framework.util.SmsUtil;
import com.futvan.z.framework.util.StringUtil;
import com.futvan.z.framework.util.SystemUtil;
@Controller
public class ZformAction extends SuperAction{
	@Autowired
	private ZformService zformService;


	/**
	 * 导出功能包
	 * @param packageType 包类型0:运行包 2：源码包
	 * @param zids 功能ID集
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/export_form_zip")
	public ResponseEntity<byte[]> export_form_zip(String zids) throws Exception {
		ResponseEntity<byte[]> response = null;
		if(z.isNotNull(zids)) {
			//创建文件头信息
			HttpHeaders headers = new HttpHeaders();
			headers.setContentDispositionFormData("attachment", "export_form_"+DateUtil.getDateTime("yyyyMMddHHmm")+".zip");
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			//生成Excel文件流
			byte[]  file = zformService.export_form_zip(zids);
			response = new ResponseEntity<byte[]>(file,headers, HttpStatus.CREATED);;
		}else {
			z.Exception("导出功能包异常：zids is null");
		}
		return response;
	}

	/**
	 * 打开数据导入页面
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/import_data")
	public ModelAndView import_data() throws Exception {
		ModelAndView model = new ModelAndView("common/form/import_data");
		return model;
	}

	@RequestMapping(value="/import_data_todb")
	public @ResponseBody Result import_data_todb(String url) throws Exception {
		Result result = new Result();
		StringBuffer msg = new StringBuffer();
		if(z.isNotNull(url)) {
			url = StringUtil.UrlDecode(url);
			//验证文件
			Result cr = checkDataFile(url);
			if(cr.getCode().equals(Code.SUCCESS)) {
				//执行导入
				File f = new File(String.valueOf(cr.getData()));
				if(f.exists() && f.isFile()) {
					//解析Excel
					Workbook book= Workbook.getWorkbook(f);
					Sheet[] ss = book.getSheets();
					boolean isOk = true;
					int SaveNum = 0;//成功保存记录数
					for (Sheet st : ss) {
						Cell tableNameCell=st.getCell(1,1);
						if(z.isNotNull(tableNameCell) && z.isNotNull(tableNameCell.getContents())) {
							String tableName = tableNameCell.getContents();
							z_form_table table = z.tables.get(tableName);
							if(z.isNotNull(table)) {
								//获取字段数
								int column_num = 0;
								for(z_form_table_column tc:table.getZ_form_table_column_list()) {
									if("0".equals(tc.getIs_hidden()) || "zid".equals(tc.getColumn_id()) || "pid".equals(tc.getColumn_id())) {
										column_num = column_num+1;
									}
								}
								if(column_num>0) {
									//数据行开始行号为 字段数+4行
									column_num = column_num + 4;

									for(int i=column_num;i<st.getRows();i++){
										HashMap<String,String> bean = new HashMap<String,String>();
										bean.put("tableId", table.getTable_id());

										for(int j=0;j<column_num-4;j++){
											String value = st.getCell(j,i).getContents();
											if(z.isNotNull(value)) {
												String columnName = st.getCell(0, j+3).getContents();
												z_form_table_column cellColumn = z.columns.get(table.getTable_id()+"_"+columnName);
												if(z.isNotNull(cellColumn)) {
													bean.put(cellColumn.getColumn_id(), value);
												}else {
													isOk = false;
													msg.append("【"+st.getName()+"】sheet中，表名【"+tableName+"】字段【"+columnName+"】未找到对应字段信息，无法导入数据").append("\r\n");
												}
											}
										}

										//保存到数据库
										Result save_r = zformService.Save(bean);
										if(!Code.SUCCESS.equals(save_r.getCode())) {
											isOk = false;
											int rowseq = i+1;
											msg.append("【"+st.getName()+"】sheet中，【第"+rowseq+"行】 保存失败 ："+bean.toString()).append("\r\n");
										}else {
											SaveNum = SaveNum+1;
										}

									}
								}else {
									isOk = false;
									msg.append("【"+st.getName()+"】sheet中，表名【"+tableName+"】字段数为0，无法导入数据").append("\r\n");
								}

							}else {
								isOk = false;
								msg.append("【"+st.getName()+"】sheet中，表名【"+tableName+"】无效，未找到对应表信息").append("\r\n");
							}
						}else {
							isOk = false;
							msg.append("【"+st.getName()+"】sheet不是有效数据导入模板，未找到表名信息").append("\r\n");
						}
					}

					if(isOk) {
						result.setCode(Code.SUCCESS);
						result.setMsg("数据导入成功，共"+SaveNum+"记录");
					}else {
						result.setCode(Code.ERROR);
					}

				}else {
					result.setCode(Code.ERROR);
					result.setMsg("文件验证成功后，未找到可导入文件");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg(cr.getMsg());
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("请先上传数据导入文件");
		}
		return result;
	}

	@RequestMapping(value="/import_data_check")
	public @ResponseBody Result import_data_check(String url) throws Exception {
		Result result = new Result();
		if(z.isNotNull(url)) {
			url = StringUtil.UrlDecode(url);
			//验证文件
			Result cr = checkDataFile(url);
			if(cr.getCode().equals(Code.SUCCESS)) {
				result = cr;
				if(z.isNull(result.getMsg())) {
					result.setMsg("数据检查成功，可以执行导入");
				}
			}else {
				result.setCode(Code.ERROR);
				result.setMsg(cr.getMsg());
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("请先上传数据导入文件");
		}
		return result;
	}

	/**
	 * 验证文件有效性
	 * @param url
	 */
	private Result checkDataFile(String url) {
		Result r = new Result();
		StringBuffer msg = new StringBuffer();
		try {
			if(z.isNotNull(url)) {
				//下载文件到本地
				String filename = z.newNumber()+".xls";
				String fpath = HttpUtil.download(url, System.getProperty("web.root")+"/temp/importExcel", filename);
				if(z.isNotNull(fpath)) {
					//设置本地文件路径，供导入数据库使用
					r.setData(fpath);
					Workbook book= Workbook.getWorkbook(new File(fpath));
					Sheet[] ss = book.getSheets();
					if(ss.length>0) {
						boolean isOk = true;
						for (Sheet st : ss) {
							Cell tableNameCell=st.getCell(1,1);
							if(z.isNotNull(tableNameCell) && z.isNotNull(tableNameCell.getContents())) {
								String tableName = tableNameCell.getContents();
								z_form_table table = z.tables.get(tableName);
								if(z.isNotNull(table)) {
									//获取字段数
									int column_num = 0;
									for(z_form_table_column tc:table.getZ_form_table_column_list()) {
										if("0".equals(tc.getIs_hidden()) || "zid".equals(tc.getColumn_id()) || "pid".equals(tc.getColumn_id())) {
											column_num = column_num+1;
										}
									}
									if(column_num>0) {
										//数据行开始行号为 字段数+4行
										column_num = column_num + 4;
										for(int i=column_num;i<st.getRows();i++){
											for(int j=0;j<column_num-4;j++){
												String value = st.getCell(j,i).getContents();
												if(z.isNotNull(value)) {
													String columnName = st.getCell(0, j+3).getContents();
													z_form_table_column cellColumn = z.columns.get(table.getTable_id()+"_"+columnName);
													if(z.isNotNull(cellColumn)) {
														//验证值与字段类型是否匹配
														Result cvc = checkValueForColumn(value,cellColumn);
														if(!Code.SUCCESS.equals(cvc.getCode())) {
															isOk = false;
															int rowseq = i+1;
															int colseq = j+1;
															msg.append("【"+st.getName()+"】sheet中，【第"+rowseq+"行 -第"+colseq+"列】数据验证出错："+cvc.getMsg()).append("\r\n");
														}
													}else {
														isOk = false;
														msg.append("【"+st.getName()+"】sheet中，表名【"+tableName+"】字段【"+columnName+"】未找到对应字段信息，无法导入数据").append("\r\n");
													}
												}
											}
										}
									}else {
										isOk = false;
										msg.append("【"+st.getName()+"】sheet中，表名【"+tableName+"】字段数为0，无法导入数据").append("\r\n");
									}

								}else {
									isOk = false;
									msg.append("【"+st.getName()+"】sheet中，表名【"+tableName+"】无效，未找到对应表信息").append("\r\n");
								}
							}else {
								isOk = false;
								msg.append("【"+st.getName()+"】sheet不是有效数据导入模板，未找到表名信息").append("\r\n");
							}
						}
						if(isOk) {
							r.setCode(Code.SUCCESS);
						}else {
							r.setCode(Code.ERROR);
						}
					}else {
						r.setCode(Code.ERROR);
						msg.append("导入模板，没有有效sheet页").append("\r\n");
					}
				}else {
					r.setCode(Code.ERROR);
					msg.append("获取导入文件出错，下载执行失败。").append("\r\n");
				}
			}else {
				r.setCode(Code.ERROR);
				msg.append("url is null").append("\r\n");
			}
		} catch (Exception e) {
			r.setCode(Code.ERROR);
			msg.append(StringUtil.ExceptionToString(e)).append("\r\n");

		}
		r.setMsg(msg.toString());
		return r;
	}

	/**
	 * 验证值与字段类型是否匹配
	 * @param value
	 * @param cellColumn
	 * @return
	 */
	private Result checkValueForColumn(String value, z_form_table_column column) {
		Result result = new Result();
		result.setCode(Code.SUCCESS);
		value = value.trim();
		if("1".equals(column.getIs_null()) && z.isNull(value)) {
			result.setCode(Code.ERROR);
			result.setMsg("字段："+column.getColumn_name()+" 要求不可为空");
		}else {
			if(z.isNotNull(value)) {
				if("0".equals(column.getColumn_type())) {//文本
				}else if("1".equals(column.getColumn_type())) {//多行文本
				}else if("2".equals(column.getColumn_type())) {//数字
					try {
						BigDecimal valuenum = new BigDecimal(value);
					} catch (Exception e) {
						result.setCode(Code.ERROR);
						result.setMsg("字段："+column.getColumn_name()+" 输入值无效，输入值不是数字");
					}
				}else if("3".equals(column.getColumn_type())) {//文件
				}else if("4".equals(column.getColumn_type())) {//图片
				}else if("5".equals(column.getColumn_type())) {//多选
					z_code c = z.code.get(column.getP_code_id());
					String[] valuearray = value.split(",");
					for (int i = 0; i < valuearray.length; i++) {
						boolean valueisOK = false;
						String v = valuearray[i];
						for (z_code_detail cd : c.getZ_code_detail_list()) {
							if(v.equals(cd.getZ_value())) {
								valueisOK = true;
							}
						}
						if(!valueisOK) {
							result.setCode(Code.ERROR);
							result.setMsg("字段："+column.getColumn_name()+" 输入值无效，请参考输入示例输入。");
						}
					}
				}else if("6".equals(column.getColumn_type())) {//单选
					z_code c = z.code.get(column.getP_code_id());
					boolean valueisOK = false;
					for (z_code_detail cd : c.getZ_code_detail_list()) {
						if(value.equals(cd.getZ_value())) {
							valueisOK = true;
						}
					}
					if(!valueisOK) {
						result.setCode(Code.ERROR);
						result.setMsg("字段："+column.getColumn_name()+" 输入值无效，请参考输入示例输入。");
					}
				}else if("7".equals(column.getColumn_type())) {//下拉框
					z_code c = z.code.get(column.getP_code_id());
					boolean valueisOK = false;
					for (z_code_detail cd : c.getZ_code_detail_list()) {
						if(value.equals(cd.getZ_value())) {
							valueisOK = true;
						}
					}
					if(!valueisOK) {
						result.setCode(Code.ERROR);
						result.setMsg("字段："+column.getColumn_name()+" 输入值无效，请参考输入示例输入。");
					}
				}else if("8".equals(column.getColumn_type())) {//Z5
					String sql = "select zid from "+column.getZ5_table()+" where "+column.getZ5_value()+" = '"+value+"'";
					String z5zid = sqlSession.selectOne("selectone", sql);
					if(z.isNull(z5zid)) {
						result.setCode(Code.ERROR);
						result.setMsg("字段："+column.getColumn_name()+" 输入值无效，无法在关联表【"+column.getZ5_table()+"】中找到【"+value+"】对应记录");
					}
				}else if("9".equals(column.getColumn_type())) {//日期
					try {
						SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
						formatter.setLenient(false);
						formatter.parse(value);
					} catch (Exception e) {
						result.setCode(Code.ERROR);
						result.setMsg("字段："+column.getColumn_name()+" 输入值无效，请输入日期格式记录。例：yyyy-mm-dd");
					}
				}else if("10".equals(column.getColumn_type())) {//日期时间
					try {
						SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						formatter.setLenient(false);
						formatter.parse(value);
					} catch (Exception e) {
						result.setCode(Code.ERROR);
						result.setMsg("字段："+column.getColumn_name()+" 输入值无效，请输入日期时间格式记录。例：yyyy-MM-dd HH:mm:ss");
					}
				}else if("11".equals(column.getColumn_type())) {//HTML输入框
				}else if("12".equals(column.getColumn_type())) {//源码输入框
				}
			}
		}
		return result;
	}

	/**
	 * 下载导入数据模板
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/download_import_template")
	public ResponseEntity<byte[]> download_import_template(@RequestParam HashMap<String,String> bean) throws Exception {
		String zid = bean.get("zid");
		if(z.isNotNull(zid)) {
			z_form f = z.forms.get(zid);
			if(z.isNotNull(f)) {
				//创建文件头信息
				HttpHeaders headers = new HttpHeaders();
				headers.setContentDispositionFormData("attachment", f.getForm_id()+".xls");
				headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
				//定义单元格样式
				//样式1
				WritableFont wf1 = new WritableFont(WritableFont.ARIAL,20);  
				WritableCellFormat f1 = new WritableCellFormat(wf1);
				f1.setBackground(Colour.GRAY_25);
				f1.setAlignment(Alignment.CENTRE);  
				f1.setVerticalAlignment(VerticalAlignment.CENTRE);  
				//样式2
				WritableFont wf2 = new WritableFont(WritableFont.ARIAL,12,WritableFont.BOLD);  
				WritableCellFormat f2 = new WritableCellFormat(wf2);
				f2.setAlignment(Alignment.LEFT);
				f2.setBackground(Colour.GRAY_25);
				f2.setVerticalAlignment(VerticalAlignment.CENTRE); 
				f2.setBorder(Border.ALL, BorderLineStyle.THIN);  
				f2.setWrap(true);//是否换行 

				//样式2r
				WritableFont wf2r = new WritableFont(WritableFont.ARIAL,12,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.RED);  
				WritableCellFormat f2r = new WritableCellFormat(wf2r);
				f2r.setAlignment(Alignment.LEFT);
				f2r.setBackground(Colour.GRAY_25);
				f2r.setVerticalAlignment(VerticalAlignment.CENTRE); 
				f2r.setBorder(Border.ALL, BorderLineStyle.THIN);  
				f2r.setWrap(true);//是否换行 

				//样式3
				WritableFont wf3 = new WritableFont(WritableFont.ARIAL,12);  
				WritableCellFormat f3 = new WritableCellFormat(wf3);
				f3.setAlignment(Alignment.LEFT);
				f3.setBackground(Colour.GRAY_25);
				f3.setVerticalAlignment(VerticalAlignment.CENTRE);  
				f3.setBorder(Border.ALL, BorderLineStyle.THIN);  
				f3.setWrap(true);//是否换行 

				//样式3r
				WritableFont wf3r = new WritableFont(WritableFont.ARIAL,12,WritableFont.NO_BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.RED);  
				WritableCellFormat f3r = new WritableCellFormat(wf3r);
				f3r.setAlignment(Alignment.LEFT);
				f3r.setBackground(Colour.GRAY_25);
				f3r.setVerticalAlignment(VerticalAlignment.CENTRE);  
				f3r.setBorder(Border.ALL, BorderLineStyle.THIN);  
				f3r.setWrap(true);//是否换行 

				//生成Excel文件流
				byte[] file = null;
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				WritableWorkbook wwb = Workbook.createWorkbook(out); 
				//获取所有表信息
				List<z_form_table> tableList = f.getZ_form_table_list();
				for (int i = 0; i < tableList.size(); i++) {
					z_form_table table = z.tablesForZid.get(tableList.get(i).getZid());

					//创建工作表
					if(z.isNotNull(table.getParent_table_id())) {
						z_form_table ptable = z.tables.get(table.getParent_table_id());
						wwb.createSheet(table.getTable_title()+"#上级主表@"+ptable.getTable_title(), i);
					}else {
						wwb.createSheet(table.getTable_title(), i);
					}

					//获取工作表 
					WritableSheet ws = wwb.getSheet(i);
					int row = 0;
					//生成表头
					ws.mergeCells(0, 0, 10, 0);
					ws.addCell(new Label(0,0,table.getTable_title()+"导入模板",f1));
					ws.addCell(new Label(0,1,"表名：",f2));
					ws.addCell(new Label(1,1,table.getTable_id(),f2));
					//合并
					ws.mergeCells(1, 1, 10, 1);
					ws.addCell(new Label(0,2,"字段标识",f2));
					ws.addCell(new Label(1,2,"字段名称",f2));
					ws.addCell(new Label(2,2,"字段类型",f2));
					ws.addCell(new Label(3,2,"是否必填",f2));
					ws.addCell(new Label(4,2,"输入值示例",f2));
					ws.mergeCells(4, 2, 10, 2);
					row = 3;
					//生成字段头行
					List<z_form_table_column> columnList = table.getZ_form_table_column_list();
					for (int y = 0; y < columnList.size(); y++) {
						if(z.isNotNull(columnList.get(y))){
							z_form_table_column column = columnList.get(y);
							if("0".equals(column.getIs_hidden()) && !"zid".equals(column.getColumn_id()) && !"pid".equals(column.getColumn_id())) {//判读是否隐藏
								//字段标识
								ws.addCell(new Label(0,row,column.getColumn_id(),f3));
								//字段名称
								ws.addCell(new Label(1,row,column.getColumn_name(),f3));
								//字段类型
								String column_type_code_value = z.codeValue.get("column_type_"+column.getColumn_type());
								ws.addCell(new Label(2,row,column_type_code_value,f3));
								//添加是否必填
								String isNotNull = z.codeValue.get("yesorno_"+column.getIs_null());
								if("是".equals(isNotNull)) {
									ws.addCell(new Label(3,row,isNotNull,f3r));
								}else {
									ws.addCell(new Label(3,row,isNotNull,f3));
								}
								//输入值示例
								ws.addCell(new Label(4,row,getImportExcelColumnExampleInfo(column),f3));
								ws.mergeCells(4, row, 10, row);
								row = row+1;
							}
						}
					}

					//添加字段说明主键
					ws.addCell(new Label(0,row,"zid",f3));
					ws.addCell(new Label(1,row,"主键",f3));
					ws.addCell(new Label(2,row,"文本",f3));
					ws.addCell(new Label(3,row,"",f3));
					ws.addCell(new Label(4,row,"单表新增时不需要输入，多表新增时需要输入，并且明细表PID需要填写主表主键。",f3));
					ws.mergeCells(4, row, 10, row);
					row = row+1;
					//添加字段说明外键
					if(z.isNotNull(table.getParent_table_id())) {
						ws.addCell(new Label(0,row,"pid",f3));
						ws.addCell(new Label(1,row,"外键",f3));
						ws.addCell(new Label(2,row,"文本",f3));
						ws.addCell(new Label(3,row,"",f3));
						ws.addCell(new Label(4,row,"必须输入主表的主键",f3));
						ws.mergeCells(4, row, 10, row);
						row = row+1;
					}

					//设置冻结列
					SheetSettings st =  ws.getSettings();
					st.setVerticalFreeze(row+1);
					//生成数据行头
					int cellNum = 0;
					for (int y = 0; y < columnList.size(); y++) {
						if(z.isNotNull(columnList.get(y))){
							z_form_table_column column = columnList.get(y);
							if("0".equals(column.getIs_hidden()) && !"zid".equals(column.getColumn_id()) && !"pid".equals(column.getColumn_id())) {//判读是否隐藏
								//添加字段列
								String isNotNull = z.codeValue.get("yesorno_"+column.getIs_null());
								if("是".equals(isNotNull)) {
									ws.addCell(new Label(cellNum,row,column.getColumn_name(),f2r));
								}else {
									ws.addCell(new Label(cellNum,row,column.getColumn_name(),f2));
								}
								//设置列宽
								ws.setColumnView(cellNum, 20);
								cellNum = cellNum+1;
							}

						}
					}

					ws.addCell(new Label(cellNum,row,"zid#主键",f2));
					ws.setColumnView(cellNum, 20);
					cellNum = cellNum+1;
					if(z.isNotNull(table.getParent_table_id())) {
						ws.addCell(new Label(cellNum,row,"pid#外键："+table.getParent_table_id()+".zid",f2));
						ws.setColumnView(cellNum, 20);
					}
				}
				wwb.write();
				wwb.close();
				file = out.toByteArray();
				out.flush();
				out.close();
				//返回文件流
				return new ResponseEntity<byte[]>(file,headers, HttpStatus.CREATED);
			}else {
				z.Exception("zid无效，未找到关联表单信息。");
				return null;
			}
		}else {
			z.Exception("zid is null");
			return null;
		}
	}

	/**
	 * 生成导入字段示例说明信息
	 * @param column
	 * @return
	 */
	private String getImportExcelColumnExampleInfo(z_form_table_column column) {
		StringBuffer result = new StringBuffer();
		if("0".equals(column.getColumn_type())) {//文本
			result.append("直接输入文本内容。");
		}else if("1".equals(column.getColumn_type())) {//多行文本
			result.append("直接输入多行文本内容。");
		}else if("2".equals(column.getColumn_type())) {//数字
			result.append("直接输入数字内容。输入的数字会按字段定义小数位数，自动格式化。");
		}else if("3".equals(column.getColumn_type())) {//文件
			result.append("直接输入文件URL地址信息。");
		}else if("4".equals(column.getColumn_type())) {//图片
			result.append("直接输入图片URL地址信息。");
		}else if("5".equals(column.getColumn_type())) {//多选
			z_code c = z.code.get(column.getP_code_id());
			StringBuffer keyValueList = new StringBuffer();
			for (z_code_detail cd : c.getZ_code_detail_list()) {
				keyValueList.append(cd.getZ_value()+",");
			}
			result.append("输入值范围："+keyValueList+",输入多个值中间用英文逗号分隔。例：XX,XX,XX");
		}else if("6".equals(column.getColumn_type())) {//单选
			z_code c = z.code.get(column.getP_code_id());
			StringBuffer keyValueList = new StringBuffer();
			for (z_code_detail cd : c.getZ_code_detail_list()) {
				keyValueList.append(cd.getZ_value()+",");
			}
			result.append("输入值范围："+keyValueList);
		}else if("7".equals(column.getColumn_type())) {//下拉框
			z_code c = z.code.get(column.getP_code_id());
			StringBuffer keyValueList = new StringBuffer();
			for (z_code_detail cd : c.getZ_code_detail_list()) {
				keyValueList.append(cd.getZ_value()+",");
			}
			result.append("输入值范围："+keyValueList);
		}else if("8".equals(column.getColumn_type())) {//Z5
			result.append("直接输入Z5显示字段值。例：字段关联表为用户表，显示字段为姓名。就直接输入姓名");
		}else if("9".equals(column.getColumn_type())) {//日期
			result.append("直接日期数据。例：2020-01-01");
		}else if("10".equals(column.getColumn_type())) {//日期时间
			result.append("直接日期时间数据。例：2020-01-01 08:30:20");
		}else if("11".equals(column.getColumn_type())) {//HTML输入框
			result.append("直接输入HTML内容。");
		}else if("12".equals(column.getColumn_type())) {//源码输入框
			result.append("直接输入源码文本内容。");
		}
		return result.toString();
	}

	/**
	 * 创建标准按钮自定义方法
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/create_custom_function_code_button")
	public @ResponseBody Result create_custom_function_code_button(@RequestParam HashMap<String,String> bean) throws Exception {
		return zformService.create_custom_function_code_button(bean);
	}

	/**
	 * 创建自定义按钮java代码
	 * @param tableId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/CreateButtonJavaCode")
	public @ResponseBody Result CreateButtonJavaCode(String pid_id,String button_id_id,String function_type) throws Exception {
		Result result = new Result();
		if(z.isNotNull(pid_id)) {
			if(z.isNotNull(function_type)) {
				//获取工程路径
				String project_path = z.sp.get("project_path");

				z_form_table table = z.tablesForZid.get(pid_id);

				//根据表id，获取formId
				String formId = sqlSession.selectOne("selectone", "SELECT c.form_id FROM z_form c  INNER JOIN z_form_table d ON c.zid = d.pid WHERE d.zid = '"+pid_id+"'");

				//获取项目ID
				StringBuffer getprojectidsql = new StringBuffer();
				getprojectidsql.append(" SELECT c.project_id FROM z_project c ");
				getprojectidsql.append(" INNER JOIN z_form f ON c.zid = f.project_id ");
				getprojectidsql.append(" INNER JOIN z_form_table ft ON f.zid = ft.pid  ");
				getprojectidsql.append(" WHERE ft.zid = '"+pid_id+"' ");
				String projectid = sqlSession.selectOne("selectone", getprojectidsql);

				//创建JAVA源码路径
				String packPath = project_path+"\\src\\main\\java\\com\\futvan\\z\\"+projectid+"\\"+formId;
				FileUtil.mkdirs(packPath);

				//创建文件
				//根据路径获取加载文件
				String tableIdUpper = StringUtil.firstLetterToUpper(table.getTable_id());//大写
				String buttonIdLower = StringUtil.firstLetterToUpper(button_id_id);//
				File f = new File(project_path+"\\src\\main\\java\\com\\futvan\\z\\"+projectid+"\\"+formId+"\\"+tableIdUpper+buttonIdLower+"ButtonAction.java");
				//如果未找到文件
				if (!f.exists()) {
					if (!f.getParentFile().exists()){
						f.getParentFile().mkdirs();
					}
					//创建文件
					f.createNewFile();
					//创建输入流
					OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(f), "UTF-8");
					BufferedWriter writer = new BufferedWriter(write);
					writer.write("package com.futvan.z."+projectid+"."+formId+";\n");
					writer.write("import java.util.HashMap;\n");
					writer.write("import com.futvan.z.framework.core.SuperAction;\n");
					writer.write("import com.futvan.z.framework.common.bean.Code;\n");
					writer.write("import com.futvan.z.framework.common.bean.Result;\n");
					writer.write("import com.futvan.z.framework.common.service.CommonService;\n");
					writer.write("import org.springframework.stereotype.Controller;\n");
					writer.write("import org.springframework.web.servlet.ModelAndView;\n");
					writer.write("import org.springframework.web.bind.annotation.RequestMapping;\n");
					writer.write("import org.springframework.web.bind.annotation.RequestParam;\n");
					writer.write("import org.springframework.web.bind.annotation.ResponseBody;\n");
					writer.write("import org.springframework.beans.factory.annotation.Autowired;\n");
					writer.write("@Controller\n");
					writer.write("public class "+tableIdUpper+buttonIdLower+"ButtonAction extends SuperAction{\n");
					writer.write("\n");
					writer.write("	@Autowired\n");
					writer.write("	private CommonService commonService;\n");
					writer.write("\n");
					if("0".equals(function_type)) {
						//路径新页面方法
						writer.write("	@RequestMapping(value=\"/"+button_id_id+"\")\n");
						writer.write("	public ModelAndView "+button_id_id+"(@RequestParam HashMap<String,String> bean) throws Exception {\n");
						writer.write("		ModelAndView model = new ModelAndView(\""+projectid+"/"+formId+"/"+button_id_id+"\");\n");
						writer.write("		\n");
						writer.write("		return model;\n");
						writer.write("	}\n");
					}
					if("1".equals(function_type)) {
						//返回json方法
						writer.write("	@RequestMapping(value=\"/"+button_id_id+"\")\n");
						writer.write("	public @ResponseBody Result "+button_id_id+"(@RequestParam HashMap<String,String> bean) throws Exception {\n");
						writer.write("		Result result = new Result();\n");
						writer.write("		\n");
						writer.write("		return result;\n");
						writer.write("	}\n");
					}
					writer.write("}\n");
					writer.close();
					write.close();
				}

				result.setCode(Code.SUCCESS);
				result.setMsg("代码创建成功");
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("function_type is null");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("pid_id is null");
		}
		return result;
	}

	/**
	 * 根据TableId获取表ZID
	 * @param tableId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getTableZidForTableId")
	public @ResponseBody Result getTableZidForTableId(String tableId) throws Exception {
		Result result = new Result();
		z_form_table table = z.tables.get(tableId);
		if(z.isNotNull(table)) {
			String zid = table.getZid();
			result.setCode(Code.SUCCESS);
			result.setData(zid);
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("根据表ID："+tableId+"  未找到表对象信息。");
		}
		return result;
	}

	/**
	 * 重新生成表
	 * @param bean
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/AgainCreateDBTable")
	public @ResponseBody Result AgainCreateDBTable(@RequestParam HashMap<String,String> bean) throws Exception {
		Result result = new Result();
		if(z.isNotNull(bean)) {
			String table_id = bean.get("table_id");
			if(z.isNotNull(table_id)) {
				result = zformService.AgainCreateDBTable(table_id);
			}else {
				result.setCode(Code.ERROR);
				result.setMsg("重新生成表执行失败|table_id is null");
			}
		}else {
			result.setCode(Code.ERROR);
			result.setMsg("重新生成表执行失败|bean is null");
		}
		return result;
	}

	@RequestMapping(value="/z_form_insert")
	public @ResponseBody Result z_form_insert(@RequestParam HashMap<String,String> bean) throws Exception {
		return zformService.z_form_insert(bean,request);
	}

	@RequestMapping(value="/z_form_update")
	public @ResponseBody Result z_form_update(@RequestParam HashMap<String,String> bean) throws Exception {
		return zformService.z_form_update(bean,request);
	}

	@RequestMapping(value="/z_form_delete")
	public @ResponseBody Result z_form_delete(@RequestParam HashMap<String,String> bean) throws Exception {
		return zformService.z_form_delete(bean,request);
	}

	@RequestMapping(value="/z_form_table_insert")
	public @ResponseBody Result z_form_table_insert(@RequestParam HashMap<String,String> bean) throws Exception {
		Result result = zformService.z_form_table_insert(bean,request);
		//添加基础菜单
		zformService.CreateMenu(bean);
		return result;
	}

	@RequestMapping(value="/z_form_table_update")
	public @ResponseBody Result z_form_table_update(@RequestParam HashMap<String,String> bean) throws Exception {
		Result result = zformService.z_form_table_update(bean,request);
		//添加基础菜单
		zformService.CreateMenu(bean);

		//判读基本按钮是
		return result;
	}

	@RequestMapping(value="/z_form_table_delete")
	public @ResponseBody Result z_form_table_delete(@RequestParam HashMap<String,String> bean) throws Exception {
		return zformService.z_form_table_delete(bean,request);
	}

	@RequestMapping(value="/z_form_table_column_insert")
	public @ResponseBody Result z_form_table_column_insert(@RequestParam HashMap<String,String> bean) throws Exception {
		if(z.isNull(bean.get("column_help")) && z.isNotNull(bean.get("column_name"))) {
			bean.put("column_help", bean.get("column_name"));
		}
		return zformService.z_form_table_column_insert(bean,request);
	}

	@RequestMapping(value="/z_form_table_column_update")
	public @ResponseBody Result z_form_table_column_update(@RequestParam HashMap<String,String> bean) throws Exception {
		if(z.isNull(bean.get("column_help")) && z.isNotNull(bean.get("column_name"))) {
			bean.put("column_help", bean.get("column_name"));
		}
		return zformService.z_form_table_column_update(bean,request);
	}

	@RequestMapping(value="/z_form_table_column_delete")
	public @ResponseBody Result z_form_table_column_delete(@RequestParam HashMap<String,String> bean) throws Exception {
		return zformService.z_form_table_column_delete(bean,request);
	}

	@RequestMapping(value="/z_form_table_button_insert")
	public @ResponseBody Result z_form_table_button_insert(@RequestParam HashMap<String,String> bean) throws Exception {
		return zformService.z_form_table_button_insert(bean,request);
	}

	@RequestMapping(value="/z_form_table_button_update")
	public @ResponseBody Result z_form_table_button_update(@RequestParam HashMap<String,String> bean) throws Exception {
		return zformService.z_form_table_button_update(bean,request);
	}

	@RequestMapping(value="/z_form_table_button_delete")
	public @ResponseBody Result z_form_table_button_delete(@RequestParam HashMap<String,String> bean) throws Exception {
		return zformService.z_form_table_button_delete(bean,request);
	}
}
